﻿using CRM.Models;
using CRM.Services;
using System.Linq;
using CRM.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Identity;
using CRM.Enums;
using CRM.ViewModels.User;
using System.Transactions;
using System.Collections.Generic;

namespace CRM.Controllers.UserManage
{
    public class UserEmployeeController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> userManager;
        private readonly UserService _UserService;
        private readonly CompanyService _CompanyService;

        public UserEmployeeController(MyDbContext dbContext, UserManager<User> userManager, UserService userService, CompanyService companyService)
        {
            _dbContext = dbContext;
            this.userManager = userManager;
            _UserService = userService;
            _CompanyService = companyService;
        }


        /// <summary>
        /// 获取员工用户列表条件信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public ResultStruct GetEmployeeSearchList()
        {
            var u = userManager.GetUserAsync(User).Result;
            var rule = new
            {
                add = true,
                edit = true,
                del = true,
            };

            Company CompanyInfo = _CompanyService.GetInfo(u.CompanyId);
            int Num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);

            var CompanyConfig = new
            {
                IsOpenUser = CompanyInfo.IsOpenUser,
                OpenUserNum = CompanyInfo.OpenUserNum - Num
            };


            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetAllRuleTemplate(u.CompanyId, u.OemId);
            var ResultsRuleTemplates = new Dictionary<int, RuleTemplateService.ChooseData>();
            ResultsRuleTemplates = RuleTemplates.ToDictionary(k => k.Id);


            UserGroupService UserGroupService = new(_dbContext);
            var Group = UserGroupService.GetAllGroup(u.CompanyId, u.OemId);
            var ResultsGroup = new Dictionary<int, UserGroupService.ChooseData>();
            ResultsGroup = Group.ToDictionary(k => k.Id);

            var data = new
            {
                ruleTemplates = ResultsRuleTemplates,
                rule = rule,
                group = ResultsGroup,
                companyConfig = CompanyConfig
            };
            return Success(data);
        }

        /// <summary>
        /// 获取员工列表信息
        /// </summary>
        /// <param name="Name"></param>
        /// <param name="GroupId"></param>
        /// <param name="RuleId"></param>
        /// <param name="State"></param>
        /// <returns></returns>
        [HttpGet("[Action]")]
        public async Task<ResultStruct> GetEmployeeList([FromQuery] string Name, [FromQuery] int? GroupId, [FromQuery] int? RuleId, [FromQuery] States? State)
        {
            var u = userManager.GetUserAsync(User).Result;

            IQueryable<User> sqlQuery = _dbContext.Users.
               Where(i => i.CompanyId == u.CompanyId).
               Where(i => i.OemId == u.OemId).
               Where(i => i.Type == Models.User.Types.Employee).
               Where(i => i.Pid == u.Id);

            if (!string.IsNullOrEmpty(Name))
            {
                sqlQuery = sqlQuery.Where(i => i.HashCode == Helper.GetDeterministicHashCode(Name));
            }

            if (State.HasValue)
            {
                sqlQuery = sqlQuery.Where(i => i.State == State);
            }

            if (GroupId != null)
            {
                sqlQuery = sqlQuery.Where(i => i.GroupId == GroupId);
            }

            if (RuleId != null)
            {
                sqlQuery = sqlQuery.Where(i => i.RuleId == RuleId);
            }


            var data = await sqlQuery.OrderBy(i => i.State).OrderByDescending(i => i.Id).ToPaginateAsync(Request);
            return Success(data);
        }

        /// <summary>
        /// 新增员工
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public async Task<ResultStruct> SubAddInfo(EmployeeSubAdd RequestData)
        {
            //检测账号名是否存在
            var res = await _dbContext.Users.Where(m => m.UserName == RequestData.UserName).FirstOrDefaultAsync();
            if (res != null)
            {
                return Error(null, "用户名已经存在");
            }

            var u = userManager.GetUserAsync(User).Result;
            //当前公司信息
            Company companyInfo = _CompanyService.GetInfo(u.CompanyId);
            int num = _UserService.GetUserNum(u.Id, u.CompanyId, u.OemId);
            var openUserNum = companyInfo.OpenUserNum - num;
            if (openUserNum < 1 && companyInfo.IsOpenUser == Company.IsOpenUsers.DISABLE)
            {
                return Error(message: "无法开通更多用户");
            }
            //权限模版信息
            RuleTemplateService RuleTemplateService = new(_dbContext);
            var RuleTemplates = RuleTemplateService.GetRuleTemplateInfo(RequestData.RuleId, u.CompanyId, u.OemId);


            using (var scope = _dbContext.Database.BeginTransaction())//创建事务
            {
                try
                {
                    //用户组未选择，新增用户组
                    if (RequestData.GroupId == 0)
                    {
                        UserGroupService UserGroupService = new(_dbContext);
                        RequestData.GroupId = await UserGroupService.InitUserGroup(u.CompanyId, u.OemId, RequestData.UserName);
                    }

                    //添加员工账号
                    var NewUsermodel = _UserService.InitEmployeeUser(RequestData, u);
                    var AddUserRet = await userManager.CreateAsync(NewUsermodel, RequestData.Password);
                    var AddRoleRet = await userManager.AddToRoleAsync(NewUsermodel, "employee");

                    //绑定员工权限
                    var AddAuthRet = await userManager.AddClaimsAsync(NewUsermodel, RuleTemplates.GetClaims(u.OemId));

                    //增加创建用户信息日志
                    //创建用户信息日志
                    var AddLogRet = _UserService.AddUserLog(NewUsermodel.Id, "创建用户", u);

                    scope.Commit();//重点，事务的提交
                }
                catch (Exception e)
                {
                    scope.Rollback();
                    return Error(e.Message);
                }
            }

            return Success();
        }

        /// <summary>
        /// 获取员工编辑信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public ResultStruct GetEmployeeInfo(GetDataId RequestData)
        {
            var u = userManager.GetUserAsync(User).Result;
            //用户可编辑信息
            var Info = _UserService.GetEditEmployeeUser(RequestData.Id, u.CompanyId);
            return Success(Info);
        }

        /// <summary>
        /// 更新员工信息
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        [HttpPost("[Action]")]
        public ResultStruct SubEditInfo(EmployeeSubEdit RequestData)
        {
            User UserInfo = _UserService.GetInfo(RequestData.Id);
            if (UserInfo == null) return Error(message: "无权操作");

            var u = userManager.GetUserAsync(User).Result;

            using (var scope = new CommittableTransaction())//创建事务
            {
                try
                {

                    //更新用户信息
                    _UserService.EditEmployeeUser(RequestData, UserInfo);

                    //增加更新用户信息日志
                    _UserService.AddUserLog(UserInfo.Id, "修改用户信息", u);


                    scope.Commit();//重点，事务的提交
                }
                catch (Exception e)
                {
                    //scope.Rollback();
                    scope.Dispose();
                    return Error(e.Message);
                }
            }

            return Success();
        }
    }
}
